package cn.edu.sjtu.process_management.config;

import cn.edu.sjtu.process_management.exception.model.BpmnException;
import cn.edu.sjtu.process_management.exception.model.FileException;
import cn.edu.sjtu.process_management.exception.model.RequestException;
import cn.edu.sjtu.process_management.exception.model.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.lang.reflect.Method;

/**
 * @author loumoon
 * @date 2019-12-08 18:39
 */
@Configuration
public class AsyncExceptionConfig implements AsyncConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(AsyncExceptionConfig.class);

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SpringAsyncExceptionHandler();
    }

    class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {

            switch (throwable.getClass().getName()) {
                case "cn.edu.sjtu.process_management.exception.model.ServiceException":
                    logger.warn("Processing ServiceException at " + ((ServiceException) throwable).getService() + ": {}",
                            ((ServiceException) throwable).getStatus().getMessage());
                    break;
                case "cn.edu.sjtu.process_management.exception.model.RequestException":
                    logger.warn("Processing RequestException: {}", ((RequestException) throwable).getStatus().getMessage());
                    break;
                case "cn.edu.sjtu.process_management.exception.model.FileException":
                    logger.warn("Processing FileException: {}", ((FileException) throwable).getStatus().getMessage());
                    break;
                case "cn.edu.sjtu.process_management.exception.model.BpmnException":
                    logger.warn("Processing BpmnException: {}", ((BpmnException) throwable).getStatus().getMessage());
                    break;
                default: // 未定义的异常
                    logger.warn("Processing Exception: {}", throwable.getMessage());
                    throwable.printStackTrace();
                    break;
            }
        }
    }
}